package com.pj.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.project.model.pojo.SpCategory;
import com.pj.project.model.vo.SpCategoryVO;
import com.pj.project.service.SpCategoryService;
import com.pj.project.model.mapper.SpCategoryMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author hanwu
* @description 针对表【sp_category(目录表)】的数据库操作Service实现
* @createDate 2022-12-17 23:01:19
*/
@Service
public class SpCategoryServiceImpl extends ServiceImpl<SpCategoryMapper, SpCategory>
    implements SpCategoryService{

    @Resource
    SpCategoryMapper saSpCategoryMapper;

    @Override
    public List<SpCategoryVO> listVo(Long id) {
//        创建vo对象
        List<SpCategoryVO> spCategoryVOList = new ArrayList<>();
        recursivelyFindCategories(spCategoryVOList,Long.parseLong("0"),id);
        return spCategoryVOList;
    }

    /**
     * 递归查询
     * @param categoryVOList  vo
     * @param parentId 父级id
     */
    private void recursivelyFindCategories(List<SpCategoryVO> categoryVOList, Long parentId,Long roleId) {
        //递归获取所有子类别，并组合成为一个“目录树”
        List<SpCategory> categoryList = saSpCategoryMapper.selectCategoriesByParentId(parentId,roleId);
        if(!CollectionUtils.isEmpty(categoryList)){
            categoryList.forEach(category->{
                SpCategoryVO categoryVO = new SpCategoryVO();
//                拷贝对象
                BeanUtils.copyProperties(category, categoryVO);
                categoryVOList.add(categoryVO);
                recursivelyFindCategories(categoryVO.getChildren(),categoryVO.getId(),roleId);
            });
        }
    }

}




